package com.jbp.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jbp.dao.PropertyDao;
import com.jbp.exception.RRException;
import com.jbp.model.Property;
import com.jbp.redis.RedisConfigService;
import com.jbp.service.PropertyService;
import com.jbp.utils.encryptUtils.RsaEncryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.jbp.utils.PageUtils;
import com.jbp.utils.Query;
import java.util.Map;

/**
 * 系统配置(Property)表服务实现类
 * @author cc
 * @since 2020-08-31 18:43:53
 */
@Service
public class PropertyServiceImpl extends ServiceImpl<PropertyDao, Property> implements PropertyService {
    @Autowired
    private RedisConfigService redisConfigService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<Property> queryWrapper = new QueryWrapper<>();
        if (params.get("id") != null){
            queryWrapper.like("id",params.get("id"));
        }
        IPage<Property> page = this.page(
                new Query<Property>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public String getV(String k) {
        //缓存10s
        long ttl = 1L * 10;
        String v = null;
        if(redisConfigService.exists(k)) {
            v = (String) redisConfigService.get(k);
        } else {
            Property property = getOne(new QueryWrapper<Property>().eq("k", k));
            v = property==null ? null :  property.getV();
            redisConfigService.set(k, v, ttl);
        }
        return v;
    }

    /**抽奖消耗的金币*/
    @Override
    public int getCoin(String poolType) {
        String v = getV("coin_" + poolType);
        if (v==null) {
            throw new RRException("参数错误");
        }
        return Integer.parseInt(v);
    }

    @Override
    public double getDouble(String k) {
        return Double.parseDouble(getV(k));
    }

    @Override
    public int getInt(String k) {
        return Integer.parseInt(getV(k));
    }

    //解密
    @Override
    public String decrypt(String encodeStr){
        try {
            String privateKey = getV("encrypt_private_key");
            String out = RsaEncryptUtil.decrypt(encodeStr, privateKey);
            if (out==null) {
                throw new RRException("错误");
            }
            return out;
        } catch (Exception e) {
            throw new RRException("错误");
        }
    }
}